"""
算法管理API端点
Algorithm Management API Endpoints
"""
import logging
from typing import List, Dict, Any, Optional, Union
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel
from datetime import datetime
import json

logger = logging.getLogger(__name__)
router = APIRouter()

# 六大AI服务配置及其具体算法
AI_SERVICES_WITH_ALGORITHMS = {
    'campus_behavior_monitoring': {
        'name': '校园行为监控',
        'algorithms': {
            'person_detection': '人员检测算法',
            'behavior_analysis': '行为分析算法',
            'abnormal_behavior': '异常行为识别',
            'crowd_gathering': '人群聚集检测',
            'violence_detection': '暴力行为检测'
        }
    },
    'campus_crowd_safety': {
        'name': '校园人群安全',
        'algorithms': {
            'crowd_density': '人群密度分析',
            'crowd_flow': '人流量统计',
            'evacuation_route': '疏散路径规划',
            'safety_monitoring': '安全监控算法',
            'emergency_detection': '紧急情况检测'
        }
    },
    'campus_energy_management': {
        'name': '校园能源管理',
        'algorithms': {
            'lighting_control': '照明控制算法',
            'occupancy_detection': '空间占用检测',
            'energy_optimization': '能耗优化算法',
            'equipment_monitoring': '设备监控算法',
            'power_analysis': '电力分析算法'
        }
    },
    'campus_environment_hygiene': {
        'name': '校园环境卫生',
        'algorithms': {
            'waste_detection': '垃圾检测算法',
            'cleanliness_assessment': '清洁度评估',
            'hygiene_monitoring': '卫生监控算法',
            'cleaning_efficiency': '清洁效率分析',
            'maintenance_alert': '维护提醒算法'
        }
    },
    'intelligent_classroom_quality': {
        'name': '智能课堂质量',
        'algorithms': {
            'attention_analysis': '注意力分析',
            'participation_tracking': '参与度跟踪',
            'learning_assessment': '学习效果评估',
            'classroom_environment': '课堂环境监测',
            'interaction_analysis': '互动分析算法'
        }
    },
    'teaching_quality_assessment': {
        'name': '教学质量评估',
        'algorithms': {
            'teacher_behavior': '教师行为分析',
            'teaching_style': '教学风格识别',
            'student_engagement': '学生参与度分析',
            'content_delivery': '内容传达效果',
            'feedback_analysis': '反馈分析算法'
        }
    }
}

# 生成所有算法的状态存储
algorithm_status = {}
for service_id, service_info in AI_SERVICES_WITH_ALGORITHMS.items():
    for alg_id, alg_name in service_info['algorithms'].items():
        full_alg_id = f"{service_id}_{alg_id}"
        algorithm_status[full_alg_id] = 'running' if hash(full_alg_id) % 3 == 0 else 'inactive'

# 保持向后兼容的AI_SERVICES
AI_SERVICES = {k: v['name'] for k, v in AI_SERVICES_WITH_ALGORITHMS.items()}

# 摄像头绑定数据库操作
def init_camera_bindings_table():
    """初始化摄像头绑定表"""
    from database.simple_db import get_database_manager
    
    try:
        db = get_database_manager()
        with db.get_connection() as conn:
            # 创建摄像头算法绑定表
            conn.execute('''
                CREATE TABLE IF NOT EXISTS camera_algorithm_bindings (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    camera_id TEXT NOT NULL,
                    camera_name TEXT NOT NULL,
                    algorithms TEXT NOT NULL,  -- JSON格式存储算法列表
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    UNIQUE(camera_id)
                )
            ''')
            
            # 创建索引
            conn.execute('CREATE INDEX IF NOT EXISTS idx_bindings_camera ON camera_algorithm_bindings(camera_id)')
            
            logger.info("摄像头绑定表初始化完成")
    except Exception as e:
        logger.error(f"初始化摄像头绑定表失败: {e}")

# 初始化绑定表
init_camera_bindings_table()


class AlgorithmModel(BaseModel):
    """算法模型"""
    id: str
    name: str
    type: str
    version: str = "1.0.0"
    description: Optional[str] = None
    status: str = "inactive"
    config: Dict[str, Any] = {}
    created_at: Optional[str] = None
    updated_at: Optional[str] = None


from typing import Union

class CameraBindingModel(BaseModel):
    """摄像头绑定模型"""
    camera_id: Union[str, int]  # 允许字符串或数字
    camera_name: str
    algorithms: List[Dict[str, Any]]
    
    class Config:
        # 自动转换类型
        str_strip_whitespace = True
        
    def __init__(self, **data):
        # 确保camera_id总是字符串
        if 'camera_id' in data:
            data['camera_id'] = str(data['camera_id'])
        super().__init__(**data)


@router.get("/algorithms")
async def get_algorithms(
    page: int = Query(1, ge=1),
    size: int = Query(10, ge=1, le=100),
    status: Optional[str] = Query(None),
    type: Optional[str] = Query(None),
    search: Optional[str] = Query(None)
):
    """获取算法列表"""
    try:
        algorithms = []
        
        logger.info(f"开始生成算法列表，AI服务数量: {len(AI_SERVICES_WITH_ALGORITHMS)}")
        
        # 遍历所有AI服务及其具体算法
        for service_id, service_info in AI_SERVICES_WITH_ALGORITHMS.items():
            service_name = service_info['name']
            logger.info(f"处理服务: {service_id} - {service_name}")
            
            # 为每个具体算法创建条目
            for alg_id, alg_name in service_info['algorithms'].items():
                logger.info(f"  创建算法: {alg_id} - {alg_name}")
                full_alg_id = f"{service_id}_{alg_id}"
                
                algorithm = {
                    "id": full_alg_id,
                    "name": alg_name,
                    "type": service_id,
                    "service_name": service_name,
                    "algorithm_type": alg_id,
                    "version": "1.0.0",
                    "description": f"{service_name} - {alg_name}",
                    "status": algorithm_status.get(full_alg_id, 'inactive'),
                    "config": {
                        "confidence_threshold": 0.7,
                        "detection_interval": 5,
                        "max_detections": 10
                    },
                    "created_at": datetime.now().isoformat(),
                    "updated_at": datetime.now().isoformat(),
                    "isRunning": algorithm_status.get(full_alg_id) == 'running',
                    "accuracy": 80 + (hash(full_alg_id) % 20),
                    "processedFrames": 500 + (hash(full_alg_id) % 5000)
                }
                
                # 应用过滤条件
                if status and algorithm["status"] != status:
                    continue
                if type and algorithm["type"] != type:
                    continue
                if search and (search.lower() not in algorithm["name"].lower() and 
                             search.lower() not in service_name.lower()):
                    continue
                    
                algorithms.append(algorithm)
        
        # 按服务类型和算法名称排序
        algorithms.sort(key=lambda x: (x["service_name"], x["name"]))
        
        # 分页
        total = len(algorithms)
        start = (page - 1) * size
        end = start + size
        paginated_algorithms = algorithms[start:end]
        
        logger.info(f"返回算法列表: {len(paginated_algorithms)} 个算法，总计 {total} 个")
        
        return {
            "code": 200,
            "msg": "查询成功",
            "total": total,
            "rows": paginated_algorithms
        }
    except Exception as e:
        logger.error(f"获取算法列表失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/algorithms/{algorithm_id}/start")
async def start_algorithm(algorithm_id: str):
    """启动算法"""
    try:
        # 检查算法是否存在
        if algorithm_id not in algorithm_status:
            # 检查是否是服务级别的ID
            if algorithm_id in AI_SERVICES:
                # 启动该服务下的所有算法
                for service_id, service_info in AI_SERVICES_WITH_ALGORITHMS.items():
                    if service_id == algorithm_id:
                        for alg_id in service_info['algorithms'].keys():
                            full_alg_id = f"{service_id}_{alg_id}"
                            algorithm_status[full_alg_id] = 'running'
                        logger.info(f"服务 {algorithm_id} 下的所有算法启动成功")
                        return {"code": 200, "msg": "启动成功"}
            else:
                raise HTTPException(status_code=404, detail="算法不存在")
        
        algorithm_status[algorithm_id] = 'running'
        logger.info(f"算法 {algorithm_id} 启动成功")
        
        return {
            "code": 200,
            "msg": "启动成功"
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"启动算法失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/algorithms/{algorithm_id}/stop")
async def stop_algorithm(algorithm_id: str):
    """停止算法"""
    try:
        # 检查算法是否存在
        if algorithm_id not in algorithm_status:
            # 检查是否是服务级别的ID
            if algorithm_id in AI_SERVICES:
                # 停止该服务下的所有算法
                for service_id, service_info in AI_SERVICES_WITH_ALGORITHMS.items():
                    if service_id == algorithm_id:
                        for alg_id in service_info['algorithms'].keys():
                            full_alg_id = f"{service_id}_{alg_id}"
                            algorithm_status[full_alg_id] = 'inactive'
                        logger.info(f"服务 {algorithm_id} 下的所有算法停止成功")
                        return {"code": 200, "msg": "停止成功"}
            else:
                raise HTTPException(status_code=404, detail="算法不存在")
        
        algorithm_status[algorithm_id] = 'inactive'
        logger.info(f"算法 {algorithm_id} 停止成功")
        
        return {
            "code": 200,
            "msg": "停止成功"
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"停止算法失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/algorithm-models")
async def get_available_models():
    """获取可用算法模型"""
    try:
        models = []
        
        # 返回所有具体算法作为模型
        for service_id, service_info in AI_SERVICES_WITH_ALGORITHMS.items():
            service_name = service_info['name']
            
            for alg_id, alg_name in service_info['algorithms'].items():
                full_alg_id = f"{service_id}_{alg_id}"
                
                model = {
                    "model_id": full_alg_id,
                    "id": full_alg_id,
                    "name": alg_name,
                    "type": service_id,
                    "service_name": service_name,
                    "algorithm_type": alg_id,
                    "description": f"{service_name} - {alg_name}",
                    "version": "1.0.0",
                    "status": "active",
                    "created_at": datetime.now().isoformat(),
                    "updated_at": datetime.now().isoformat()
                }
                models.append(model)
        
        logger.info(f"返回算法模型: {len(models)} 个模型")
        
        return {
            "code": 200,
            "msg": "查询成功",
            "data": models
        }
    except Exception as e:
        logger.error(f"获取算法模型失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))





# 摄像头绑定相关端点
@router.get("/camera-bindings", tags=["摄像头绑定"])
async def get_camera_bindings():
    """获取摄像头绑定列表"""
    try:
        from database.simple_db import get_database_manager
        
        db = get_database_manager()
        with db.get_connection() as conn:
            # 查询所有绑定，按摄像头分组
            cursor = conn.execute('''
                SELECT camera_id, camera_name, camera_location, algorithm_id, algorithm_name, 
                       algorithm_type, model_id, priority, config_params, enabled, status,
                       created_at, updated_at
                FROM camera_algorithm_bindings
                ORDER BY camera_id, priority, updated_at DESC
            ''')
            
            # 按摄像头ID分组算法
            camera_groups = {}
            for row in cursor.fetchall():
                camera_id = row[0]
                if camera_id not in camera_groups:
                    camera_groups[camera_id] = {
                        "camera_id": camera_id,
                        "camera_name": row[1] or f"摄像头 {camera_id}",
                        "camera_location": row[2] or "",
                        "algorithms": [],
                        "created_at": row[11],
                        "updated_at": row[12]
                    }
                
                # 构建算法信息
                algorithm = {
                    "algorithm_id": row[3],
                    "algorithm_name": row[4] or row[3],
                    "service_id": row[5] or "unknown",
                    "algorithm_type": row[5] or "unknown",
                    "model_id": row[6] or "default_model",
                    "enabled": bool(row[9]),
                    "priority": row[7] or 1,
                    "status": row[10] or "active"
                }
                
                # 解析配置参数
                if row[8]:
                    try:
                        config = json.loads(row[8]) if isinstance(row[8], str) else {}
                    except:
                        config = {}
                else:
                    config = {
                        "confidence_threshold": 0.8,
                        "detection_interval": 5,
                        "max_detections": 10
                    }
                algorithm["config"] = config
                
                camera_groups[camera_id]["algorithms"].append(algorithm)
                
                # 更新最新的时间戳
                if row[12] > camera_groups[camera_id]["updated_at"]:
                    camera_groups[camera_id]["updated_at"] = row[12]
            
            # 转换为列表格式
            bindings = []
            for camera_id, group in camera_groups.items():
                binding_data = {
                    "id": f"binding_{camera_id}",
                    "camera_id": camera_id,
                    "camera_name": group["camera_name"],
                    "algorithms": group["algorithms"],
                    "created_at": group["created_at"],
                    "updated_at": group["updated_at"]
                }
                bindings.append(binding_data)
            
            logger.info(f"获取摄像头绑定成功: {len(bindings)} 个绑定")
            return {
                "code": 200,
                "msg": "查询成功",
                "data": bindings
            }
    except Exception as e:
        logger.error(f"获取摄像头绑定失败: {e}")
        # 返回空列表而不是抛出异常
        return {
            "code": 200,
            "msg": "查询成功",
            "data": []
        }


@router.post("/camera-bindings", tags=["摄像头绑定"])
async def create_camera_binding(binding: CameraBindingModel):
    """创建摄像头算法绑定"""
    try:
        from database.simple_db import get_database_manager
        
        db = get_database_manager()
        
        with db.get_connection() as conn:
            # 先删除该摄像头的所有现有绑定
            conn.execute(
                'DELETE FROM camera_algorithm_bindings WHERE camera_id = ?',
                (binding.camera_id,)
            )
            
            # 为每个算法创建单独的绑定记录
            for algorithm in binding.algorithms:
                config_json = json.dumps(algorithm.get('config', {}), ensure_ascii=False)
                
                conn.execute('''
                    INSERT INTO camera_algorithm_bindings 
                    (camera_id, camera_name, camera_location, algorithm_id, algorithm_name, 
                     algorithm_type, model_id, priority, config_params, enabled, status)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ''', (
                    binding.camera_id,
                    binding.camera_name,
                    "",  # camera_location - 可以从binding中获取如果有的话
                    algorithm.get('algorithm_id'),
                    algorithm.get('algorithm_name'),
                    algorithm.get('service_id', algorithm.get('algorithm_type', 'unknown')),
                    algorithm.get('model_id', 'default_model'),
                    algorithm.get('priority', 1),
                    config_json,
                    algorithm.get('enabled', True),
                    algorithm.get('status', 'active')
                ))
            
            # 提交事务
            conn.commit()
            logger.info(f"创建摄像头绑定成功: {binding.camera_id}, {len(binding.algorithms)} 个算法")
        
        return {
            "code": 200,
            "msg": "创建成功",
            "data": {"id": f"binding_{binding.camera_id}"}
        }
    except Exception as e:
        logger.error(f"创建摄像头绑定失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/camera-bindings/{camera_id}", tags=["摄像头绑定"])
async def update_camera_binding(camera_id: str, binding: CameraBindingModel):
    """更新摄像头算法绑定"""
    try:
        from database.simple_db import get_database_manager
        
        db = get_database_manager()
        
        with db.get_connection() as conn:
            # 检查绑定是否存在
            cursor = conn.execute(
                'SELECT id FROM camera_algorithm_bindings WHERE camera_id = ?',
                (camera_id,)
            )
            if not cursor.fetchone():
                raise HTTPException(status_code=404, detail="绑定不存在")
            
            # 删除现有绑定
            conn.execute(
                'DELETE FROM camera_algorithm_bindings WHERE camera_id = ?',
                (camera_id,)
            )
            
            # 重新创建绑定
            for algorithm in binding.algorithms:
                config_json = json.dumps(algorithm.get('config', {}), ensure_ascii=False)
                
                conn.execute('''
                    INSERT INTO camera_algorithm_bindings 
                    (camera_id, camera_name, camera_location, algorithm_id, algorithm_name, 
                     algorithm_type, model_id, priority, config_params, enabled, status)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ''', (
                    camera_id,
                    binding.camera_name,
                    "",  # camera_location
                    algorithm.get('algorithm_id'),
                    algorithm.get('algorithm_name'),
                    algorithm.get('service_id', algorithm.get('algorithm_type', 'unknown')),
                    algorithm.get('model_id', 'default_model'),
                    algorithm.get('priority', 1),
                    config_json,
                    algorithm.get('enabled', True),
                    algorithm.get('status', 'active')
                ))
            
            # 提交事务
            conn.commit()
        
        logger.info(f"更新摄像头绑定成功: {camera_id}")
        
        return {
            "code": 200,
            "msg": "更新成功"
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新摄像头绑定失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/camera-bindings/{camera_id}", tags=["摄像头绑定"])
async def delete_camera_binding(camera_id: str):
    """删除摄像头算法绑定"""
    try:
        from database.simple_db import get_database_manager
        
        db = get_database_manager()
        
        with db.get_connection() as conn:
            # 检查绑定是否存在
            cursor = conn.execute(
                'SELECT id FROM camera_algorithm_bindings WHERE camera_id = ?',
                (camera_id,)
            )
            if not cursor.fetchone():
                raise HTTPException(status_code=404, detail="绑定不存在")
            
            # 删除绑定
            conn.execute(
                'DELETE FROM camera_algorithm_bindings WHERE camera_id = ?',
                (camera_id,)
            )
            
            # 提交事务
            conn.commit()
        
        logger.info(f"删除摄像头绑定成功: {camera_id}")
        
        return {
            "code": 200,
            "msg": "删除成功"
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除摄像头绑定失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# AI服务概览端点
@router.get("/ai-services/overview", tags=["AI服务"])
async def get_ai_services_overview():
    """获取AI服务概览"""
    try:
        running_algorithms = sum(1 for status in algorithm_status.values() if status == 'running')
        total_algorithms = len(algorithm_status)
        
        services = []
        for service_id, service_info in AI_SERVICES_WITH_ALGORITHMS.items():
            service_name = service_info['name']
            
            # 计算该服务下运行中的算法数量
            service_running = sum(1 for alg_id in service_info['algorithms'].keys() 
                                if algorithm_status.get(f"{service_id}_{alg_id}") == 'running')
            service_total = len(service_info['algorithms'])
            
            services.append({
                'id': service_id,
                'name': service_name,
                'status': 'running' if service_running > 0 else 'inactive',
                'running_algorithms': service_running,
                'total_algorithms': service_total,
                'accuracy': 85 + (hash(service_id) % 15),
                'processedFrames': 1000 + (hash(service_id) % 9000),
                'lastUpdate': datetime.now().isoformat()
            })
        
        return {
            "code": 200,
            "msg": "查询成功",
            "data": {
                "runningAlgorithms": running_algorithms,
                "totalAlgorithms": total_algorithms,
                "avgAccuracy": 88.5,
                "alerts": 2,
                "services": services
            }
        }
    except Exception as e:
        logger.error(f"获取AI服务概览失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 测试端点 - 验证算法生成逻辑
@router.get("/test", tags=["测试"])
async def test_algorithm_generation():
    """测试算法生成逻辑"""
    try:
        algorithms = []
        
        logger.info(f"测试: AI服务数量: {len(AI_SERVICES_WITH_ALGORITHMS)}")
        
        for service_id, service_info in AI_SERVICES_WITH_ALGORITHMS.items():
            service_name = service_info['name']
            logger.info(f"测试: 处理服务 {service_id} - {service_name}")
            
            for alg_id, alg_name in service_info['algorithms'].items():
                full_alg_id = f"{service_id}_{alg_id}"
                logger.info(f"测试: 创建算法 {full_alg_id} - {alg_name}")
                
                algorithm = {
                    "id": full_alg_id,
                    "name": alg_name,
                    "service_name": service_name,
                    "algorithm_type": alg_id
                }
                algorithms.append(algorithm)
        
        logger.info(f"测试: 生成了 {len(algorithms)} 个算法")
        
        return {
            "code": 200,
            "msg": "测试成功",
            "total": len(algorithms),
            "algorithms": algorithms
        }
    except Exception as e:
        logger.error(f"测试失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

# 算法统计端点
@router.get("/statistics", tags=["算法统计"])
async def get_algorithm_statistics():
    """获取算法统计信息"""
    try:
        running_count = sum(1 for status in algorithm_status.values() if status == 'running')
        total_count = len(algorithm_status)
        
        return {
            "code": 200,
            "msg": "查询成功",
            "data": {
                "total_algorithms": total_count,
                "running_algorithms": running_count,
                "inactive_algorithms": total_count - running_count,
                "avg_accuracy": 88.5,
                "total_processed_frames": 50000
            }
        }
    except Exception as e:
        logger.error(f"获取算法统计失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))





# GPU状态端点
@router.get("/gpu/status", tags=["GPU监控"])
async def get_gpu_status():
    """获取GPU状态（模拟数据）"""
    try:
        import random
        
        gpu_data = {
            'id': 'gpu_0',
            'name': 'NVIDIA GeForce RTX 4090',
            'status': 'active',
            'usage': {
                'gpu': random.randint(60, 95),
                'memory': random.randint(50, 85),
                'encoder': random.randint(10, 30),
                'decoder': random.randint(5, 20)
            },
            'memory': {
                'total': 24576,  # 24GB
                'used': random.randint(6144, 18432),
                'free': 0
            },
            'temperature': {
                'current': random.randint(65, 85),
                'max': 83
            },
            'power': {
                'current': random.randint(250, 350),
                'limit': 450,
                'max': 450
            },
            'fan': {
                'speed': random.randint(40, 70)
            },
            'processes': [
                {'pid': 1234, 'name': 'python.exe', 'memory': 2048},
                {'pid': 5678, 'name': 'ai_service.exe', 'memory': 4096},
                {'pid': 9012, 'name': 'video_processor.exe', 'memory': 1024}
            ],
            'driver_version': '535.98',
            'cuda_version': '12.2'
        }
        
        # 计算free memory
        gpu_data['memory']['free'] = gpu_data['memory']['total'] - gpu_data['memory']['used']
        
        return {
            "code": 200,
            "msg": "查询成功",
            "data": gpu_data
        }
    except Exception as e:
        logger.error(f"获取GPU状态失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))
# AI服务概览端点
@router.get("/ai-services/overview", tags=["AI服务"])
async def get_ai_services_overview():
    """获取AI服务概览"""
    try:
        running_algorithms = sum(1 for status in algorithm_status.values() if status == 'running')
        total_algorithms = len(algorithm_status)
        
        services = []
        for service_id, service_info in AI_SERVICES_WITH_ALGORITHMS.items():
            service_name = service_info['name']
            
            # 计算该服务下运行中的算法数量
            service_running = sum(1 for alg_id in service_info['algorithms'].keys() 
                                if algorithm_status.get(f"{service_id}_{alg_id}") == 'running')
            service_total = len(service_info['algorithms'])
            
            services.append({
                'id': service_id,
                'name': service_name,
                'status': 'running' if service_running > 0 else 'inactive',
                'running_algorithms': service_running,
                'total_algorithms': service_total,
                'accuracy': 85 + (hash(service_id) % 15),
                'processedFrames': 1000 + (hash(service_id) % 9000),
                'lastUpdate': datetime.now().isoformat()
            })
        
        return {
            "code": 200,
            "msg": "查询成功",
            "data": {
                "runningAlgorithms": running_algorithms,
                "totalAlgorithms": total_algorithms,
                "avgAccuracy": 88.5,
                "alerts": 2,
                "services": services
            }
        }
    except Exception as e:
        logger.error(f"获取AI服务概览失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


